import abc
import copy
from abc import abstractmethod

from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
import sqlite3 as sql
import record as rec
import wav_to_string as wtos

# 需要传入__name__ 为了确定资源所在路径
app = Flask(__name__)
CORS(app, supports_credentials=True)

class Config(object):#单例模式
    SECRET_KEY = 'YRH_SECRET_KEY'

class where: #原型模式
    def __init__(self,row,col):
        self.col = col
        self.row = row

class wherecopy():
    def __init__(self):
        self.A = where()

    def __str__(self):
        return '{}, {}'.format(self.A.col, self.A.row)

class pro(metaclass=abc.ABCMeta):
    @abstractmethod
    def make(self):
        pass

class shu():
    def judge(self,aa, chessboard,t):
        c = copy.deepcopy(aa)
        print(c.col, c.row)
        total = 1
        # 上面
        while c.row - 1 > 0 and chessboard[c.row - 1][c.col] == t:
            total = total + 1
            c.row = c.row - 1

        d = copy.deepcopy(aa)
        # 下面
        while d.row + 1 < 15 and chessboard[d.row + 1][d.col] == t:
            total = total + 1
            d.row = d.row + 1

        if total >= 5:
            if t == 1:
                return "黑棋获胜"
            else:
                return "白棋获胜"
        else:
            return "继续"

class heng():
    def judge(self,aa, chessboard,t):
        c = copy.deepcopy(aa)
        print(c.col, c.row)
        total = 1
        # 左边
        while c.col - 1 > 0 and chessboard[c.row][c.col - 1] == t:
            total = total + 1
            c.col = c.col - 1

        d = copy.deepcopy(aa)
        print(c.col, c.row)
        # 右边
        while d.col + 1 < 15 and chessboard[d.row][d.col + 1] == t:
            total = total + 1
            d.col = d.col + 1

        if total >= 5:
            if t == 1:
                return "黑棋获胜"
            else:
                return "白棋获胜"
        else:
            return "继续"

class pie():
    def judge(self,aa, chessboard,t):
        c = copy.deepcopy(aa)
        print(c.col, c.row)
        total = 1
        # /上是否满足获胜条件
        # 右上
        while c.row - 1 > 0 and c.col + 1 < 15 and chessboard[c.row - 1][c.col + 1] == t:
            total = total + 1
            c.row = c.row - 1
            c.col = c.col + 1

        d = copy.deepcopy(aa)
        print(d.col, d.row)
        # 左下
        while d.row + 1 < 15 and d.col - 1 > 0 and chessboard[d.row + 1][d.col - 1] == t:
            total = total + 1
            d.row = d.row + 1
            d.col = d.col - 1

        if total >= 5:
            if t == 1:
                return "黑棋获胜"
            else:
                return "白棋获胜"
        else:
            return "继续"
class na():
    def judge(self,aa, chessboard,t):
        c = copy.deepcopy(aa)
        print(c.col, c.row)
        total = 1
        # 判断\上是否满足获胜条件
        # 左上
        while c.row - 1 > 0 and c.col - 1 > 0 and chessboard[c.row - 1][c.col - 1] == t:
            total = total + 1
            c.row = c.row - 1
            c.col = c.col - 1

        d = copy.deepcopy(aa)
        print(d.col, d.row)
        # 右下
        while d.row + 1 < 15 and d.col + 1 < 15 and chessboard[d.row + 1][d.col + 1] == t:
            total = total + 1
            d.row = d.row + 1
            d.col = d.col + 1

        if total >= 5:
            if t == 1:
                return "黑棋获胜"
            else:
                return "白棋获胜"
        else:
            return "继续"

#工厂模式
class Factory(object):
    def product(self, mobile_type):
        #垂直方向
        if mobile_type == 'shu':
            return shu()
        #/方向
        elif mobile_type == 'na':
            return na()
        #水平方向
        elif mobile_type == 'heng':
            return heng()
        #\方向
        elif mobile_type == 'pie':
            return pie()



global map
map = [[0 for i in range(15)] for j in range(15)]


# #flask中定义路由是通过装饰器来实现的，访问路由会自动调用路由下跟的方法，并将执行结果返回
@app.route('/')
def home():
    return render_template('login.html')


@app.route('/game')
def game():
    return render_template('game.html')


@app.route('/register', methods=["POST", "GET"])
def register():
    conn = sql.connect('database.db')
    print("Opened database successfully")

    # conn.execute('drop table user')
    conn.execute('create table if not exists user (name TEXT primary key, password TEXT)')
    conn.commit()
    print("Table created successfully")
    username = request.form['username']
    password = request.form['password']

    if request.method == 'POST':
        try:
            nm = request.form['username']
            psw = request.form['password']
            conn.execute("INSERT INTO user (name,password) VALUES (?,?)", (nm, psw))
            conn.commit()
            return {"code": 200, "msg": "成功"}
        except:
            conn.rollback()
            return {"code": 400, "msg": "注册失败"}
        finally:
            conn.close()


@app.route('/login', methods=["POST", "GET"])
def login():
    conn = sql.connect('database.db')
    print("Opened database successfully")
    username = request.form['username']
    password = request.form['password']

    if request.method == 'POST':
        try:
            res = conn.execute('select * from user')
            userlist = res.fetchall()
            print(userlist)
            fla = 0
            for i in range(0, len(userlist)):
                if username == userlist[i][0] and password == userlist[i][1]:
                    fla = 1
                    return {"code": 200, "msg": "成功"}
            if fla == 0:
                return {"code": 400, "msg": "账户名或密码错误"}
        except:
            return {"code": 400, "msg": "账户名或密码错误"}
        finally:
            conn.close()


@app.route('/reccontro', methods=["POST", "GET"])
def reccontro():
    if request.method == 'POST':
        r = rec.GenAudio() #工厂模式
        r.read_audio()
        r.save_wav("./templates/test.wav")

        token = wtos.fetch_token()

        speech_data = []
        with open(wtos.AUDIO_FILE, 'rb') as speech_file:
            speech_data = speech_file.read()

        length = len(speech_data)
        if length == 0:
            raise wtos.DemoError('file %s length read 0 bytes' % wtos.AUDIO_FILE)
        speech = wtos.base64.b64encode(speech_data)
        if (wtos.IS_PY3):
            speech = str(speech, 'utf-8')
        params = {'dev_pid': wtos.DEV_PID,
                  # "lm_id" : LM_ID,    #测试自训练平台开启此项
                  'format': wtos.FORMAT,
                  'rate': wtos.RATE,
                  'token': token,
                  'cuid': wtos.CUID,
                  'channel': 1,
                  'speech': speech,
                  'len': length
                  }
        post_data = wtos.json.dumps(params, sort_keys=False)
        # print post_data
        req = wtos.Request(wtos.ASR_URL, post_data.encode('utf-8'))
        req.add_header('Content-Type', 'application/json')
        try:
            begin = wtos.timer()
            f = wtos.urlopen(req)
            result_str = f.read()
            print("Request time cost %f" % (wtos.timer() - begin))
        except wtos.URLError as err:
            print('asr http response http code : ' + str(err.code))
            result_str = err.read()

        if (wtos.IS_PY3):
            result_str = str(result_str, 'utf-8')

        with open("result.txt", "w") as of:
            of.write(result_str)
        print(result_str)

        fircha = result_str[result_str.find('行') - 2]
        seccha = result_str[result_str.find('列') - 2]

        fircha2 = ''
        fircha2 = result_str[result_str.find('行') - 1]

        seccha2 = ''
        seccha2 = result_str[result_str.find('列') - 1]

        nums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']

        firnum = 0
        for i in range(0, 11):
            if nums[i] == fircha or nums[i] == fircha2:
                firnum += i

        secnum = 0
        for i in range(0, 11):
            if nums[i] == seccha or nums[i] == seccha2:
                secnum += i
        if firnum == 0 or secnum == 0:
            return {"code": 400, "data": "识别失败"}
        return {"code": 200, "data": {"row": firnum, "col": secnum}}


@app.route('/replay', methods=["POST", "GET"])
def replay():
    global map
    map = [[0 for i in range(15)] for j in range(15)]
    return {"code": 200, "msg": "成功"}


@app.route('/judge', methods=["POST"])
def judge():
    # 1黑子，2白子
    t = int(request.form['t'])
    print(t)
    tmprow = request.form['row']
    print(tmprow)
    tmpcol = request.form['col']
    print(tmpcol)
    row = int(tmprow)
    col = int(tmpcol)
    total = 1

    map[row][col] = t
    chessboard = map

    for i in range(0, 15):
        print(map[i])

    aa = where(row, col)
    factory = Factory()
    yu = factory.product('shu').judge(aa, chessboard,t)
    if yu=="继续":
        yu = factory.product('heng').judge(aa, chessboard,t)
        if yu == "继续":
            yu = factory.product('pie').judge(aa, chessboard,t)
            if yu == "继续":
                yu = factory.product('na').judge(aa, chessboard,t)
                return {"data": yu}
            else:
                return {"data": yu}
        else:
            return {"data": yu}
    else:
        return {"data": yu}
    # # 判断水平方向上是否满足获胜条件
    # # 左边
    # while col - 1 > 0 and chessboard[row][col - 1] == t:
    #     total = total + 1
    #     col = col - 1
    #
    # row = int(tmprow)
    # col = int(tmpcol)
    # # 右边
    # while col + 1 < 15 and chessboard[row][col + 1] == t:
    #     total = total + 1
    #     col = col + 1
    #
    # if total >= 5:
    #     if t == 1:
    #         return {"code": 201, "msg": "黑棋获胜"}
    #     else:
    #         return {"code": 202, "msg": "白棋获胜"}
    #
    # # 判断垂直方向上是否满足获胜条件
    # row = int(tmprow)
    # col = int(tmpcol)
    #
    #
    # #上面
    # while row - 1 > 0 and chessboard[row - 1][col] == t:
    #     total = total + 1
    #     row = row - 1
    #
    # row = int(tmprow)
    # col = int(tmpcol)
    # #下面
    # while row + 1 < 15 and chessboard[row + 1][col] == t:
    #     total = total + 1
    #     row = row + 1
    #
    # if total >= 5:
    #     if t == 1:
    #         return {"code": 201, "msg": "黑棋获胜"}
    #     else:
    #         return {"code": 202, "msg": "白棋获胜"}
    #
    # # /上是否满足获胜条件
    # row = int(tmprow)
    # col = int(tmpcol)
    # #右上
    # while row - 1 > 0 and col + 1 < 15 and chessboard[row - 1][col + 1] == t:
    #     total = total + 1
    #     row = row - 1
    #     col = col + 1
    #
    # row = int(tmprow)
    # col = int(tmpcol)
    # #左下
    # while row + 1 < 15 and col - 1 > 0 and chessboard[row + 1][col - 1] == t:
    #     total = total + 1
    #     row = row + 1
    #     col = col - 1
    #
    # if total >= 5:
    #     if t == 1:
    #         return {"code": 201, "msg": "黑棋获胜"}
    #     else:
    #         return {"code": 202, "msg": "白棋获胜"}
    #
    # # 判断\上是否满足获胜条件
    # row = int(tmprow)
    # col = int(tmpcol)
    # # 左上
    # while row - 1 > 0 and col - 1 > 0 and chessboard[row - 1][col - 1] == t:
    #     total = total + 1
    #     row = row - 1
    #     col = col - 1
    #
    # row = int(tmprow)
    # col = int(tmpcol)
    # #右下
    # while row + 1 < 15 and col + 1 < 15 and chessboard[row + 1][col + 1] == t:
    #     total = total + 1
    #     row = row + 1
    #     col = col + 1
    #
    # if total >= 5:
    #     if t == 1:
    #         return {"code": 201, "msg": "黑棋获胜"}
    #     else:
    #         return {"code": 202, "msg": "白棋获胜"}
    #
    # return {"code": 203, "msg": "继续"}


if __name__ == '__main__':
    app.config.from_object(Config())
    app.run(host='0.0.0.0', port=7777, debug=False)
